﻿import Request from '../../base/request.js?t=202511041006'
import Storage from '../../base/storage.js?t=202511041006'
import { imageBaseUrl, isImageFile, getBrowserInfo } from "../../base/utils.js?t=202511041006"
const Composition = (proxy) => {
    const data = reactive({
        activeKey: "2",
        messageTest: "",
        cid: "",
        proxy: "",
        checkFrom: {
            userName: "",
            userId: "",
            checkDate: "",
            advice: ""
        },
        s1Form: null,
        s4Form: {
            Title: "",
            PublishTime: "",
            Content: "",
            dept: ""
        },
        s4FormRule: {
            Title: { required: true, message: '请输入通知标题', trigger: 'change' },

            Content: { required: true, message: '请输入通知内容', trigger: 'change' },
        },

        form: {

            ntitle: '',
            ntime: "",
            ndept: [],
            ncontent: "",

            ptype: "",
            pdept: "",
            pwaddress: "",
            ppaddress: "",
            paim: "",
            ptime: "",
            prange: "",
            cgname: "",
            groupList: [{
                prule: "",
                pname: "",
                ptel: "",
                pduty: "",

            }],
            dateList: [{
                gtime: "",
                gdept: "",
                gmember: "",
                gmain: "",

            }],




            remark: "",


        },
        pagination: {
            total: 0,
            current: 1,
            loading: false,
            pageSize: 10,
            showTotal: total => `总共 ${total} 项`,
            defaultPageSize: 10,
            // pageSizeOptions: ['5', '10', '15', '20'], // 可不设置使用默认
            hideOnSinglePage: true, // 是否显示pagesize选择
            showQuickJumper: false, // 是否显示跳转窗

        },

        res1: [],
        res2: [],

        previewShow: false,
        imgUrl: "",
        time: [],
        planTypeList: [
            'OHSMS', 'EMS', 'QMS'
        ].map((e, i) => {

            return {
                label: e,
                value: i
            }
        }),
        fileList: [

        ],

        rules: [
            'GB/T45001-2020', 'GB/T24001-2016', 'GB/T19001-2016', '受审核方现行有效的管理体系文件', '适用于受审核方', 'OHSMS', 'EMS', '能源体系GB/T 23331-2020', '(适用时)其他:'
        ].map((e, i) => {

            return {
                label: e,
                value: i
            }
        }),
        itemRender: (data) => {



            let uid = data.file.uid
            const text = h('div', { style: 'cursor:pointer;margin-left:10px' }, data.file.name)
            const previewBtn = h('img', { style: 'cursor:pointer;margin:0 4px;', onclick: () => { methods.btnPreview(uid) }, src: "../Bussiness/img/svg/preview.svg", width: 20, height: 22 }, '预览')
            const downloadBtn = h('img', { style: 'cursor:pointer;margin:0 4px;', onclick: () => { methods.btnDownLoad(uid) }, src: "../Bussiness/img/svg/download.svg", width: 20, height: 22 }, '下载')
            const deleteBtn = h('img', { style: 'cursor:pointer;margin:0 4px;', onclick: () => { methods.btnDelete(uid) }, src: "../Bussiness/img/svg/delete.svg", width: 18, height: 22 }, '删除')
            var btns = ""
            console.log(data.file, 'data.file')

            if (isImageFile(data.file.url)) {
                btns = h('div', { style: "display:flex;" }, [
                    previewBtn,
                    downloadBtn,
                    deleteBtn
                ])
            } else {
                btns = h('div', { style: "display:flex;" }, [
                    downloadBtn,
                    deleteBtn
                ])
            }

            return h('div', { style: 'margin-top:10px; width:100%;display:flex;justify-content:space-between' }, [
                text, btns
            ])

        },


        dataSource2: [],
        columns1: [
            {
                title: '成员角色',
                dataIndex: 'JobRoleName',
                key: 'JobRoleName',
                align: 'center',

            },
            {
                title: '成员职务',
                dataIndex: 'JobTitle',
                key: 'JobTitle',
                align: 'center'

            },
            {
                title: '成员姓名',
                dataIndex: 'MemberName',
                key: 'MemberName',
                align: 'center'

            },
            {
                title: '联系电话',
                dataIndex: 'Phone',
                key: 'Phone',
                align: 'center'

            },
        ],
        columns2: [
            {
                title: '时间',
                align: 'center',
                customRender: ({ text, record, index }) => {
                    const regex = /\/Date\((\d+)\)\//;
                    const match1 = text && record.StartTime.match(regex);
                    const match2 = text && record.EndTime.match(regex);
                    if (match1 && match2) {

                        let sTag = h(antd.Tag, {
                            color: "green"
                        }, { default: () => dayjs(parseInt(match1[1], 10)).format('YYYY-MM-DD HH:mm:ss') });

                        let eTag = h(antd.Tag, {
                            color: "red"
                        }, { default: () => dayjs(parseInt(match2[1], 10)).format('YYYY-MM-DD HH:mm:ss') });

                        let divide = h('div', {

                        }, { default: () => '-' });

                        return h(antd.Space, {

                        }, () => [sTag, divide, eTag]);
                    } else {
                        return ""
                    }
                },
            },
            {
                title: '审核组',
                align: 'center',
                customRender: ({ text, record, index }) => {
                    return record.TeamInfo.TeamName
                }

            },
            {
                title: '成员',
                align: 'center',
                customRender: ({ text, record, index }) => {
                    return record.TeamInfo.MemberList.map(e => `${e.MemberName}(${e.UserNo})`).toString()
                }

            },
            {
                title: '受审核部门',
                dataIndex: 'DepartmentName',
                key: 'DepartmentName',
                align: 'center'
            },
            {

                title: '重点审核要素',
                dataIndex: 'Factor',
                key: 'Factor',
                align: 'center'
            }
        ],

        itemRender: (data) => {
     


            let uid = data.file.uid
            const text = h('div', { style: 'cursor:pointer;margin-left:10px' }, data.file.name)
            const previewBtn = h('img', { style: 'cursor:pointer;margin:0 4px;', onclick: () => { methods.btnPreview(uid) }, src: "../Bussiness/img/svg/preview.svg", width: 20, height: 22 }, '预览')
            const downloadBtn = h('img', { style: 'cursor:pointer;margin:0 4px;', onclick: () => { methods.btnDownLoad(uid) }, src: "../Bussiness/img/svg/download.svg", width: 20, height: 22 }, '下载')
            const deleteBtn = h('img', { style: 'cursor:pointer;margin:0 4px;', onclick: () => { methods.btnDelete(uid) }, src: "../Bussiness/img/svg/delete.svg", width: 18, height: 22 }, '删除')
            var btns = ""

            if (isImageFile(data.file.url)) {
                btns = h('div', { style: "display:flex;" }, [
                    previewBtn,
                    downloadBtn,
                    //deleteBtn
                ])
            } else {
                btns = h('div', { style: "display:flex;" }, [
                    downloadBtn,
                    //deleteBtn
                ])
            }

            return h('div', { style: 'margin-top:10px; width:100%;display:flex;justify-content:space-between' }, [
                text, btns
            ])

        },
    })
    let params = toRefs(data)

    //const previewParams = ref({
    //    visible: params.previewShow.value,
    //    onVisibleChange: methods.setVisible
    //}) 

    const methods = {

        addGroup: () => {
            let obj = {
                prule: "",
                pname: "",
                ptel: "",
                pemail: "",
            }

            params.form.value.groupList.push(obj)
        },
        delGroup: (index) => {
            params.form.value.groupList.splice(index, 1)
        },


        addDate: () => {
            let obj = {
                gtime: "",
                gdept: "",
                gmember: "",
                gmain: "",
            }

            params.form.value.dateList.push(obj)
        },
        delDate: (index) => {
            params.form.value.dateList.splice(index, 1)
        },




        downloadfun: (name, url) => {
            // 创建a标签
            let a = document.createElement('a')
            // 定义下载名称
            a.download = name
            // 隐藏标签
            a.style.display = 'none'
            a.target = "view_window"
            // 设置文件路径
            a.href = url
            // 将创建的标签插入dom
            document.body.appendChild(a)
            // 点击标签，执行下载
            a.click()
            // 将标签从dom移除
            document.body.removeChild(a)
        },
        setVisible: (value) => {
            params.previewShow.value = value;
        },
        btnPreview: (e) => {
            let item = params.fileList.value.find(es => es.uid == e)
            item.url = item.FilePath || item.url
            params.imgUrl.value = item.url
            methods.setVisible(true)
        },
        btnDownLoad: (e) => {
            let item = params.fileList.value.find(es => es.uid == e)
            item.url = item.FilePath || item.url
            const { name, url } = item
            methods.downloadfun(name, url)

        },
        btnDelete: (e) => {
            params.fileList.value = params.fileList.value.filter(es => es.uid != e)
        },

        customRequest: (e) => {

        },

        init: () => {
              getBrowserInfo().catch(err => { console.log(err)})
            if (proxy) {
                params.proxy.value = proxy
            }
            const { message } = antd
            params.messageTest.value = message
            params.messageTest.value.config({
                top: `10vh`,
                duration: 7,
                maxCount: 1,
                rtl: true,
            });
          
            function queryURLParams() {
                const searchParams = window.location.search.substring(1).split("&");
                const params = {};

                for (const param of searchParams) {
                    const [key, value] = param.split("=");
                    params[key] = value;
                }

                return params;
            }
            const { id } = queryURLParams()
            params.cid.value = id
            let info = Storage.get('AccountInfo', true)
            Request({
                url: "/Account/createJwtToken",
                method: 'post',
                data: {
                    "userName": info && info.UserNo
                }
            }).then(res => {
                Storage.set('token', res.Data,true)

                Request({
                    url: "/performance/GetPlanTotalDetail",
                    method: 'post',
                    data: {
                        FormId: id
                    }
                }).then(res => {
                    params.s4Form.value = res.Data.Step4
                    params.s4Form.value.dept = params.s4Form.value.Departments
                    const regex = /\/Date\((\d+)\)\//;
                    const match1 = params.s4Form.value.PublishTime.match(regex);

                    params.s4Form.value.PublishTime = dayjs(parseInt(match1[1], 10)).format('YYYY-MM-DD HH:mm:ss')
                    params.s1Form.value = res.Data.Step1
                    const match2 = params.s1Form.value.UpdateTime.match(regex);
                    params.s1Form.value.CaseManageUser.UserName = `${params.s1Form.value.CaseManageUser.UserName}(${params.s1Form.value.CaseManageUser.UserNo})`
                    params.s1Form.value.UpdateTime = dayjs(parseInt(match2[1], 10)).format('YYYY-MM-DD HH:mm:ss')


                    params.s1Form.value.TypeId = params.s1Form.value.TypeName && params.s1Form.value.TypeName.map(e => e.ConfigName).toString()

                    params.s1Form.value.TargetId = params.s1Form.value.TargetName && params.s1Form.value.TargetName.map(e => {
                        if (!e.IsInput) {
                            return e.ConfigName
                        } else {
                            return params.s1Form.value.OtherTarget
                        }

                    }).toString()

                    params.s1Form.value.GuideLine = params.s1Form.value.GuideLineName && params.s1Form.value.GuideLineName.map(e => {
                        if (!e.IsInput) {
                            return e.ConfigName
                        } else {
                            return params.s1Form.value.OtherGuideLine
                        }

                    }).toString()
                    params.s1Form.value.DepartmentId = params.s1Form.value.DepartmentList && params.s1Form.value.DepartmentList.map(e => e.DepartmentName).toString()
                    params.s1Form.value.TargetName = params.s1Form.value.TypeName && params.s1Form.value.TypeName.map(e => e.ConfigName).toString()
                    params.fileList.value = params.s1Form.value.FileList && params.s1Form.value.FileList.map(e => {
                        return {
                            url:  e.url ? e.url : imageBaseUrl + e.FilePath.split('../..')[1] ,
                            name: e.FileName,
                            uid: e.uid,
                            FileId: e.FileId
                        }
                    })
                    params.res1.value = res.Data.Step2
                    params.dataSource2.value = res.Data.Step3
                    const match3 = res.Data.OperateLog.OperateTime.match(regex);
                    params.checkFrom.value.pzuserName = `${res.Data.OperateLog.OperateUserName}(${res.Data.OperateLog.OperateUser})`
                    params.checkFrom.value.pzcheckDate = dayjs(parseInt(match3[1], 10)).format('YYYY-MM-DD HH:mm:ss')
                })
            })
            let item = Storage.get('AccountInfo', true)
            let time = dayjs(Date.now()).format('YYYY-MM-DD HH:mm:ss')
            const { UserName, UserNo, UserId } = item
            params.checkFrom.value.userName = `${UserName}(${UserNo})`
            params.checkFrom.value.userId = UserId
            params.checkFrom.value.subTime = time


        },
        onSbumit: (flag) => {
            Request({
                url: "/performance/ApprovePlan",
                method: 'post',
                data: {
                    "FormId": params.cid.value,
                    "IsApprove": flag,
                    "Remark": params.checkFrom.value.advice
                }
            }).then(res => {
                params.messageTest.value.success(res.Msg);
                setTimeout(() => {
                    methods.onBack()
                }, 1000)

            })

        },
        onBack: () => {
            window.location.href = "/Performance/PerformancePlanPageList"
        },

        onChange: (value, dateString) => {
            params.checkFrom.value.checkDate = dateString
        },
        onOk: (res) => {
            console.log(res, 'res')
        },





    }

    const template = {
        bottomBtns: {
            template: `<div class="w-full  h-50  flex  items-center justify-end">
                    <a-space>
                        <a-button v-on:click="onBack">返回</a-button>
                    </a-space>
                </div>`,
            setup() {

                return {
                    ...params,
                    ...methods,
                };
            }

        }
    }
    return {
        ...params,
        ...methods,
        template
    }
}

export default Composition
